package com.tool.cn.use;

import java.io.File;

import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.util.StatusPrinter;

/**
 * 
 * @author wangzonghui
 * @date 2021-08-24 11:28:45
 * @Description 项目环境初始化
 */
public final class ObjectInit {
	
	/**
	 * 项目根路径
	 */
	public static String rootPath="";
	/**
	 * 配置文件路径
	 */
	public static String properFile="";
	
	private static String logFile="";
	
	private static String configName="config";
	
	/**
	 * 初始化配置和日志信息
	 */
	public static void init() {
		init(ObjectInit.class,true,"");
	}
	
	/**
	 *  初始化项目信息
	 * @param initLog 是否初始化日志配置
	 */
	public static void init(boolean initLog) {
		init(ObjectInit.class,initLog,"");
	}

	/**
	 * 初始化项目配置
	 * @param logFileName 日志文件名
	 */
	public static void init(String logFileName) {
		
		init(ObjectInit.class, true, logFileName);
	}
	
	/**
	 * 初始化项目配置
	 * @param logFileName 日志文件名
	 * @param configName 配置文件名
	 */
	public static void init(String logFileName,String configName) {
		if(!isEmpty(configName)) {
			ObjectInit.configName=configName;
		}
		
		init(ObjectInit.class, true, logFileName);
	}
	
	/**
	 * 初始化项目信息
	 * @param classFormat 引用类
	 * @param initLog 是否初始化日志配置
	 */
	public static void init(Class<?> classFormat,boolean initLog,String logFileName) {
		//LOG_HOME 初始化
		if (System.getProperty("LOG_HOME")==null||System.getProperty("LOG_HOME").length()<=0) {
			System.setProperty("LOG_HOME", getPath(classFormat));
		}
		
		//logFIleName 初始化
		if(!isEmpty(logFileName)) {
			System.setProperty("LOG_INFO", logFileName+"-info");
			System.setProperty("LOG_ERROR", logFileName+"-error");
		}else {
			System.setProperty("LOG_INFO", "info");
			System.setProperty("LOG_ERROR", "error");
		}
		
		
		if(System.getProperty("os.name").indexOf("Windows")>=0){  //windows环境
			//项目根目录
			rootPath=System.getProperty("user.dir")+File.separator;
			
			if(new File(rootPath+"pom.xml").exists()) { //maven项目
				properFile=rootPath+"src\\main\\resources\\"+configName+"-win.properties";
				logFile=rootPath+"src\\main\\resources\\logback.xml";
				
			}else { //普通项目
				properFile=rootPath+"config"+File.separator+configName+"-win.properties";
				logFile=rootPath+"config"+File.separator+"logback.xml";
			}
			
			//不存在
			if(!new File(properFile).exists()) {
				String properFileTmp=getPath(classFormat)+File.separator+"config"+File.separator+configName+".properties";
				logFile=getPath(classFormat)+File.separator+"config"+File.separator+"logback.xml";
				
				System.out.println(properFile+" No Found To Reset "+properFileTmp);
				properFile=properFileTmp;
				
			}
			
			//开发环境spring boot项目不需要初始化日志文件
			if(initLog) {
				initLogback(logFile);
			}
			
		}else {   //linux环境 -DLOG_HOME=${home}
			rootPath=getPath(classFormat)+File.separator;
			//配置文件路径
			properFile=rootPath+"config"+File.separator+configName+".properties";
			//日志路径
			logFile=rootPath+"config"+File.separator+"logback.xml";
			
			if(initLog) {
				initLogback(logFile);
			}
		}
		
	}
	
	
	/**
	 * 获取程序目录
	 */
	private static String getPath(Class<?> classFormat){
		String path = classFormat.getProtectionDomain().getCodeSource().getLocation().getPath();
		if(path.startsWith("file:")) {
			path=path.replace("file:", "");
		}
		
		if(path.startsWith("nested:")) {
			path=path.replace("nested:", "");
		}
		
		if(System.getProperty("os.name").contains("dows")){
			path = path.substring(1,path.length());
		}

		if(path.contains("jar")){
			do {
				path = path.substring(0,path.lastIndexOf("."));
				path= path.substring(0,path.lastIndexOf("/"));
			}while(path.contains("jar"));
			
		}

		return new File(path.replace("/classes/", "")).getParent();
	}
	
	public static boolean isEmpty(String str) {
		if (str == null || str.trim().isEmpty()) {
			return true;
		}
		return false;
	}
	
	/**
	 * 初始化日志配置
	 */
    private static void initLogback(String logFile) {
        File file = new File(logFile);
        if(!file.exists()){
        	System.out.println("Error: Log Config "+logFile+" No exits");
        	System.exit(0);
        }
        
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        JoranConfigurator joranConfigurator = new JoranConfigurator();
        joranConfigurator.setContext(loggerContext);
        loggerContext.reset();
//        loggerContext.putProperty("other", "路径测试"); //xml中 ${other调用}
        try {
            joranConfigurator.doConfigure(file);
        } catch (Exception e) {
        	System.out.println("Error: Init Log Config "+logFile+"  Error Of "+e.getMessage());
        	System.exit(0);
        }
        StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext);
    }

}
